<?php

namespace App\Http\Controllers\Bi;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\Finance;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

class UserController extends Controller
{

    public function index(Request $request)
    {
        if ($request->ajax()){
            $data = $request->all(['department_id','start_date','end_date']);
            if ($data['department_id']){
                $pDepartmentIds = Department::query()->where('parent_id',$data['department_id'])->pluck('id')->toArray();
                $departmentIds = array_merge($pDepartmentIds,[$data['department_id']]);
                $users = User::query()->whereIn('department_id',$departmentIds)->select(['id','nickname','department_id'])->get();
            }else{
                $users = User::query()->select(['id','nickname','department_id'])->get();
            }
            foreach ($users as $user){
                $money = Finance::query()
                    ->when($data['start_date']&&$data['end_date'],function ($q) use($data){
                        return $q->whereBetween('check_time',[$data['start_date'].' 00:00:00',$data['end_date'].' 23:59:59']);
                    })
                    ->where('check_status','=',3) // 1待审核，2审核不通过，3审核通过
                    ->where('owner_user_id','=',$user->id)
                    ->where('outin','=',1) //1收入，0支出
                    //->where('type','=',2) //1客户，2合同，3订单
                    //->where('contract_id','>',0)
                    ->sum('money');
                $user->money = round($money,2);
            }
            return $this->success('ok',$users);
        }
        return View::make('bi.user.index');
    }

}
